package com.pencilisland.pay.app.mp.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.bean.mp.app.MessageRequest;
import com.pencilisland.pay.api.bean.mp.app.MessageResponse;
import com.pencilisland.pay.api.bean.mp.app.QueryUserAddressREQ;
import com.pencilisland.pay.api.bean.mp.app.QueryUserAddressRES;
import com.pencilisland.pay.api.bean.mp.app.WxPayUnifyOrderRES;
import com.pencilisland.pay.api.bean.wxpay.WxLoginResp;
import com.pencilisland.pay.api.entity.UserAddressEntity;
import com.pencilisland.pay.api.repository.UserAddressRepository;
import com.pencilisland.pay.api.service.CacheService;
import com.pencilisland.pay.app.mp.service.MBService;

/**
 * 报文逻辑处理.查询当前用户的收货地址
 *
 * @author breeze
 */
@Service("MB_queryUserAddress")
public class QueryUserAddressMB implements MBService {

	@Autowired
	ObjectMapper objectMapper;
	@Autowired
	CacheService cacheService;
	@Autowired
	UserAddressRepository userAddressRepo;

	@Override
	public MessageResponse process(MessageRequest request) {

		WxLoginResp result = (WxLoginResp) cacheService.get(request.getSessionId());
		if (result == null || StringUtils.isEmpty(result.getOpenId())) {
			return new WxPayUnifyOrderRES(false, null, "没有登录数据");
		}

		QueryUserAddressRES res = new QueryUserAddressRES(true, null, "OK");

		List<UserAddressEntity> userAddressList = userAddressRepo.findByOpenIdOrderByCreateTimeDesc(result.getOpenId());
		if (userAddressList != null && !userAddressList.isEmpty()) {
			List<QueryUserAddressRES.ElementAddressList> elementAddressList = new ArrayList<QueryUserAddressRES.ElementAddressList>();
			for (UserAddressEntity userAddress : userAddressList) {
				QueryUserAddressRES.ElementAddressList elementAddress = new QueryUserAddressRES.ElementAddressList();
				try {
					BeanUtils.copyProperties(elementAddress, userAddress);
				} catch (Exception e) {
					e.printStackTrace();
				}
				elementAddressList.add(elementAddress);
			}
			res.setAddressList(elementAddressList);
		}
		return res;
	}

	public QueryUserAddressREQ getRequestBody(MessageRequest request) {
		return objectMapper.convertValue(request.getBody(), QueryUserAddressREQ.class);
	}

}
